package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsCompanionCategoryService;
import com.ucode.cgms.service.CgmsCompanionProductService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.cgms.service.CgmsSpecialZoneService;
import com.ucode.model.cgms.CgmsCompanionCategory;
import com.ucode.model.cgms.CgmsCompanionProduct;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.CgmsSpecialZone;
import com.ucode.model.cgms.convert.CgmsCompanionProductConvert;
import com.ucode.model.cgms.form.CgmsCompanionProductForm;
import com.ucode.model.cgms.vo.CgmsCompanionProductVO;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonReleaseStatusEnum;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.tool.validator.InEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

@Tag(name = "管理后台 - 陪玩社区系统 - 陪玩服务商品")
@RestController
@RequestMapping("/cgms/companion-product")
@Validated
public class CgmsCompanionProductController {

    @Resource
    private CgmsCompanionCategoryService cgmsCompanionCategoryService;
    @Resource
    private CgmsSpecialZoneService cgmsSpecialZoneService;
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    @Resource
    private CgmsCompanionProductService cgmsCompanionProductService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:query')")
    public ResponseResult<Paginator<CgmsCompanionProductVO>> pageList(
            @Schema(description = "标题") @RequestParam(value = "title",required = false) String title,
            @Schema(description = "专区编号") @RequestParam(value = "zoneId",required = false) Long zoneId,
            @Schema(description = "专区分类编号") @RequestParam(value = "categoryId",required = false) Long categoryId,
            @Schema(description = "提供者编号") @RequestParam(value = "providerId",required = false) Long providerId,
            @Schema(description = "状态,参见CommonReleaseStatusEnum枚举类",allowableValues = {"0","1","2"}) @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(title))
            condition.put("title", StrUtil.concat(true, title,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("zoneId",zoneId);
        condition.put("categoryId",categoryId);
        condition.put("providerId",providerId);
        condition.put("status",status);
        condition.put("deltag",false);

        Paginator<CgmsCompanionProduct> paginator = cgmsCompanionProductService.queryPageForList(condition,pageSize,pageNum);
        Paginator<CgmsCompanionProductVO> paginatorVO = CgmsCompanionProductConvert.INSTANCE.convertPage(paginator);
        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> zoneIds = new HashSet<>();
            Set<Long> categoryIds = new HashSet<>();
            Set<Long> providerIds = new HashSet<>();
            for(CgmsCompanionProductVO vo : paginatorVO.getList()){
                if(ObjUtil.isNotNull(vo.getZoneId()) && !ObjUtil.equals(vo.getZoneId(), 0L))
                    zoneIds.add(vo.getZoneId());

                if(ObjUtil.isNotNull(vo.getCategoryId()) && !ObjUtil.equals(vo.getCategoryId(), 0L))
                    categoryIds.add(vo.getCategoryId());

                if(ObjUtil.isNotNull(vo.getProviderId()) && !ObjUtil.equals(vo.getProviderId(), 0L))
                    providerIds.add(vo.getProviderId());
            }

            Map<Long, CgmsSpecialZone> specialZoneMap = cgmsSpecialZoneService.getMap(zoneIds);
            Map<Long, CgmsCompanionCategory> companionCategoryMap = cgmsCompanionCategoryService.getMap(categoryIds);
            Map<Long, CgmsCompanionUser> companionUserMap = cgmsCompanionUserService.getMap(providerIds);

            for(CgmsCompanionProductVO vo : paginatorVO.getList()){
                CgmsSpecialZone zone = specialZoneMap.get(vo.getZoneId());
                if(ObjUtil.isNotNull(zone)) {
                    vo.setZoneName(zone.getName());
                }

                CgmsCompanionCategory category = companionCategoryMap.get(vo.getCategoryId());
                if(ObjUtil.isNotNull(category)) {
                    vo.setCategoryName(category.getName());
                }
                if(ObjUtil.isNotNull(vo.getProviderId()) && !ObjUtil.equals(vo.getProviderId(), 0L)){
                    CgmsCompanionUser provider = companionUserMap.get(vo.getProviderId());
                    if(ObjUtil.isNotNull(provider)) {
                        vo.setNickname(provider.getNickName());
                        vo.setAvatar(provider.getAvatar());
                    }
                }

            }
        }

        return ResponseResult.success(paginatorVO);
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    public ResponseResult<Paginator<CgmsCompanionProduct>> simplePageList(@Schema(description = "名称")  @RequestParam(value = "name",required = false) String name,
                                                                      @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                      @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true, name,"%"));
        //condition.put("status",CommonReleaseStatusEnum.RELEASE.code);
        condition.put("deltag",false);

        Paginator<CgmsCompanionProduct> paginator = cgmsCompanionProductService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:query')")
    public ResponseResult<CgmsCompanionProductVO> getById(@PathVariable(name="id",required=true) Long id){
        CgmsCompanionProduct bean = cgmsCompanionProductService.validate(id);
        CgmsCompanionProductVO vo = CgmsCompanionProductConvert.INSTANCE.convert(bean);
        if(ObjUtil.isNotNull(bean.getZoneId())){
            CgmsSpecialZone zone = cgmsSpecialZoneService.selectByPrimaryKey(bean.getZoneId());
            if(ObjUtil.isNotNull(zone)) {
                vo.setZoneName(zone.getName());
            }
            CgmsCompanionCategory category = cgmsCompanionCategoryService.selectByPrimaryKey(bean.getCategoryId());
            if(ObjUtil.isNotNull(category)) {
                vo.setCategoryName(category.getName());
            }

            if(ObjUtil.isNotNull(vo.getProviderId()) && !ObjUtil.equals(vo.getProviderId(), 0L)){
                CgmsCompanionUser provider = cgmsCompanionUserService.selectByPrimaryKey(vo.getProviderId());
                if(ObjUtil.isNotNull(provider)) {
                    vo.setNickname(provider.getNickName());
                    vo.setAvatar(provider.getAvatar());
                }
            }
        }
        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:create')")
    public ResponseResult<Long> create(@Valid @RequestBody CgmsCompanionProductForm form) {
        CgmsCompanionProduct bean = CgmsCompanionProductConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        if(form.getOnSale()){
            bean.setStatus(CommonReleaseStatusEnum.RELEASE.getCode());
            bean.setReleaseTime(LocalDateTime.now());
        }else {
            bean.setStatus(CommonReleaseStatusEnum.DRAFT.getCode());
        }
        Long id = cgmsCompanionProductService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody CgmsCompanionProductForm form) {
        CgmsCompanionProduct bean = CgmsCompanionProductConvert.INSTANCE.convert(form);
        bean.setId(id);
        int i = cgmsCompanionProductService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids,
                                                @Schema(description = "状态",requiredMode = Schema.RequiredMode.REQUIRED,allowableValues = {"0","1","2"})
                                                @InEnum(value = CommonReleaseStatusEnum.class, message = "修改的状态值必须是 {value}")
                                                @RequestParam(value = "status",required = true) Integer status) {
        int i = cgmsCompanionProductService.updateStatus(ids, status);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = cgmsCompanionProductService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-product:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = cgmsCompanionProductService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

}
